jQuery(function($) {
    encodeURIComponent(editor_desc.html($("#texthidden").val()));
    encodeURIComponent(editor_content.html($("#contenthidden").val()));

    encodeURIComponent(editor_pre_sale_rules.html($("#hidden_pre_sale_rules").val()));
    encodeURIComponent(editor_m_special_desc.html($("#hidden_m_special_desc").val()));
    encodeURIComponent(editor_m_multifunctional_auxiliary_part.html($("#hidden_m_multifunctional_auxiliary_part").val()));

    encodeURIComponent(editor_url1.html($("#hidden_url1").val()));
    encodeURIComponent(editor_url2.html($("#hidden_url2").val()));
    encodeURIComponent(editor_url3.html($("#hidden_url3").val()));
    encodeURIComponent(editor_url4.html($("#hidden_url4").val()));
    var id_no='';
    if($("#hidden_m_id").val()==''){
        id_no=1;
    }else{
        id_no=2;
    }
    $(".hidden_pic").each(function(){
        var val= $(this).val();
        var service_url = $("#service_url").val();;
        var jsons       = "/2013/"+val;
        //$('#' + file.id).parent().find('img').remove();

        //$('#' + file.id).parent().attr('filename',data);
        if ($(".no_pic").length > 0) {
            $(".no_pic").remove();
        }
        $("<div style='max-width:200px;height:140px;float: left;text-align: center'><input type='hidden' name='upload_files' value='"+val+"' />" +
            "<img class='preview-upload-pic' style='height:110px;max-width:160px;' src='"+service_url+jsons+"'/>&nbsp;" +val+"<br/><a href='javascript:void(0);' file_name='"+val+"'class='del_pic'>删除</a><br/><br/><br/></div>").insertAfter($('#b_pic1'));
        bind_del_pic();

    });


    $("caption").eq(2).siblings().hide();
    $("caption").click(function(){
        $(this).siblings().toggle();
        var that=$(this).children('b');
        if(that.hasClass("icon-angle-down")){
            that.addClass("icon-angle-up");
            that.removeClass("icon-angle-down");
        }else{
            that.addClass("icon-angle-down");
            that.removeClass("icon-angle-up");
        }
    });
    $(".tag_txt").hide();
    $("#add_tag").click(function(){
        $(".tag_txt").show();
    });
    $("#default_tag").click(function(){
        $("#tags").val('');
        $(".tag_txt").hide();

    });
    $('[data-rel=tooltip]').tooltip();
    $(".chosen-select").chosen();
    $(".start_datetime").datetimepicker({
        format: 'yyyy-mm-dd hh:ii'
    });
    $('.start_datetime').datetimepicker('setStartDate', new Date());
    var domain_source = [];
    var tag_input = $('#sharing_domain');
    if(! ( /msie\s*(8|7|6)/.test(navigator.userAgent.toLowerCase())) )
    {
        tag_input.tagsinput({
            typeahead: {
                source: domain_source
            },
            freeInput: false
        });
    } else {
        //display a textarea for old IE, because it doesn't support this plugin or another one I tried!
        tag_input.after('<textarea id="'+tag_input.attr('id')+'" name="'+tag_input.attr('name')+'" rows="3">'+tag_input.val()+'</textarea>').remove();
    }
    loadData($("select[name=brand_id]").val());
    $("select[name=brand_id]").change(function(){
        var brand_id = $(this).val();
        loadData(brand_id);
    })
    $('#sharing_domain').on('itemAdded', function(event) {
        // event.item: contains the item
        addDomainItem(event.item);
    });
    $('input').on('itemRemoved', function(event) {
        // event.item: contains the item
        $("#serverIp").empty();
        $("#serverIp").trigger("chosen:updated");
        removeDomainItem();
    });
    $("#base_submit").click(function(){
        var m_supplier=$.trim($('input[name="m_supplier"]').val()),
            m_name =$.trim($("input[name=m_name]").val()),
            bar_code=$.trim($("input[name=bar_code]").val()),
            keyword = $.trim($("#serverIp").val()),
            kind_name=$('input[name="kind_name"]').val(),
            m_tag=$('select[name="m_tag"]').val(),
            desc=encodeURIComponent(editor_desc.html()),
            content=encodeURIComponent(editor_content.html()),
            m_price=$.trim($('input[name="m_price"]').val()),
            m_usual_price=$.trim($('input[name="m_usual_price"]').val()),
            tag_name=$('input[name="tag_name"]').val(),
            brand_id=$('select[name="brand_id"]').val(),
            kind_id=$.trim($("input[name=kind_id]").val()),
            m_spec=$('input[name="m_spec"]:checked').val();
        var serverIp = JSON.stringify($('#serverIp').val());
        var key_list =serverIp.substr(1,serverIp.length-2).replace(/,/g,",").replace(/"/g,"");

        if(m_name == ''){
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>商品名称不能为空！</span>"
            });
            return false;
        }
        if(bar_code == ''){
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>商品条码不能为空！</span>"
            });
            return false;
        }
        if (keyword == '') {
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>关键字不得为空！</span>"
            });
            return false;
        }
        if($("#machine_no>div").length>0){
            if ($('input[name="machine_no"]').is(':checked') ) {

            }else{
                bootbox.dialog({
                    message: "<span class='btn-sm btn-danger'>请选择机型！</span>"
                });
                return false;
            }
            var machine_no = $("input:checkbox[name='machine_no']:checked").map(function(index,elem) {
                return $(elem).val();
            }).get().join(',');

        }else{
            var  machine_no=' ';
        }
        if (kind_name == '') {
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请选择分类！</span>"
            });
            return false;
        }

        if (desc == '') {
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请填写描述！</span>"
            });
            return false;
        }
        if (content == '') {
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请填写详情！</span>"
            });
            return false;
        }

        if (m_usual_price == '') {
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>市场价格不能为空！</span>"
            });
            return false;
        }
        if (m_price == '') {
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>零售价不能为空！</span>"
            });
            return false;
        }
        if (tag_name == '') {
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>规格描述不能为空！</span>"
            });
            return false;
        }
        if ($('input[name="m_spec"]').is(':checked')) {

        }else{
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请选择商品规格！</span>"
            });
            return false;
        }

        var key_list =serverIp.substr(1,serverIp.length-2).replace(/,/g,",").replace(/"/g,"");
        var data="";

        if(m_tag==1){
            var m_deliver_limit_time=$('input[name="m_deliver_limit_time"]').val(),
                m_stock=$('input[name="m_stock"]').val(),
                limit_purchase_num=$('input[name="limit_purchase_num"]').val();
            if($('input[name="m_deliver_limit_time"]').val()==''){
                bootbox.dialog({
                    message: "<span class='btn-sm btn-danger'>请选择配送时间！</span>"
                });
                return false;
            }
            if($('input[name="m_stock"]').val()==''){
                bootbox.dialog({
                    message: "<span class='btn-sm btn-danger'>请填写促销数量！</span>"
                });
                return false;
            }
            if($('input[name="limit_purchase_num"]').val()==''){
                bootbox.dialog({
                    message: "<span class='btn-sm btn-danger'>最小限购数量！</span>"
                });
                return false;
            }
            if($("#hidden_m_id").val()==''){
                data={"m_supplier":m_supplier, "m_name":m_name, "bar_code":bar_code, "keyword":key_list,
                    "kind_id":kind_id, "m_tag":m_tag, "desc":desc,
                    "content":content, "m_price":m_price,
                    "m_usual_price":m_usual_price, "tag_name":tag_name,"m_spec":m_spec,"machine_no":machine_no,"brand_id":brand_id,
                    "m_deliver_limit_time":m_deliver_limit_time,"m_stock":m_stock,"limit_purchase_num":limit_purchase_num,"id_no":id_no
                };
            }else{
                var m_id=$("#hidden_m_id").val();
                data={"m_id":m_id,"m_supplier":m_supplier, "m_name":m_name, "bar_code":bar_code, "keyword":key_list,
                    "kind_id":kind_id, "m_tag":m_tag, "desc":desc,
                    "content":content, "m_price":m_price,
                    "m_usual_price":m_usual_price, "tag_name":tag_name,"m_spec":m_spec,"machine_no":machine_no,"brand_id":brand_id,
                    "m_deliver_limit_time":m_deliver_limit_time,"m_stock":m_stock,"limit_purchase_num":limit_purchase_num,"id_no":id_no
                };
            }


        }else{
            if($("#hidden_m_id").val()==''){
                data={"m_supplier":m_supplier, "m_name":m_name, "bar_code":bar_code, "keyword":key_list,
                    "kind_id":kind_id, "m_tag":m_tag, "desc":desc,
                    "content":content, "m_price":m_price,
                    "m_usual_price":m_usual_price, "tag_name":tag_name,"m_spec":m_spec,"machine_no":machine_no,"brand_id":brand_id,"id_no":id_no
                };
            }else{
                var m_id=$("#hidden_m_id").val();
                data={"m_id":m_id, "m_supplier":m_supplier, "m_name":m_name, "bar_code":bar_code, "keyword":key_list,
                    "kind_id":kind_id, "m_tag":m_tag, "desc":desc,
                    "content":content, "m_price":m_price,
                    "m_usual_price":m_usual_price, "tag_name":tag_name,"m_spec":m_spec,"machine_no":machine_no,"brand_id":brand_id,"id_no":id_no
                };
            }


        }
        var addurl=$("#addMenu").val();
        $.ajax({
            type:"POST",
            async:false,
            dataType:"json",
            url:addurl,
            data:data,
            success:function(data,textStatus){
                if(data.code==200){
                    $("#m_id").val(data.m_id);
                    bootbox.dialog({
                        message: "<span class='bigger-110'>"+data.msg+"</span>",
                        buttons:
                        {
                            "success" :
                            {
                                "label" : "<i class='icon-ok'></i> Success!",
                                "className" : "btn-sm btn-success",
                                "callback": function() {
                                    //window.close();
                                    $("caption").eq(0).siblings().hide();
                                    $("caption").eq(2).siblings().show();
                                    var speed=200;//滑动的速度
                                    $('body,html').animate({ scrollTop: 0 }, speed);
                                }
                            }
                        }
                    });
                }else{
                    bootbox.dialog({
                        message: "<span class='btn-sm btn-danger'>"+data.msg+"</span>"
                    });
                }
            },
            error:function(XMLHttpRequest,textStatus,errorThrown){
                bootbox.dialog({
                    message: "<span class='btn-sm btn-danger'>网络错误！</span>"
                });

            }
        });
    });


    $("#add_attach").click(function(){
        if($("#hidden_m_id").val()==''){
            var m_id = $("#m_id").val();
            if(m_id==''){
                bootbox.dialog({
                    message: "<span class='btn-sm btn-danger'>请先填写商品基本参数</span>"
                });
                return false;
            }
            id_no=1;
        }else{
            var m_id = $("#hidden_m_id").val();
            id_no=2;
        }


        var file_name = $("input[name='upload_files']").map(function(index,elem) {
            return $(elem).val();
        }).get().join(',');

        if(file_name==''){
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请上传图片</span>"
            });
            return false;
        }
        var url=$("#addAttach").val();
        $.ajax({
            type:"POST",
            async:false,
            dataType:"json",
            url:url,
            data:{"m_id":m_id, "file_name":file_name, "id_no":id_no},
            success:function(data,textStatus){
                if(data.code==200){
                    bootbox.dialog({
                        message: "<span class='bigger-110'>"+data.msg+"</span>",
                        buttons:
                        {
                            "success" :
                            {
                                "label" : "<i class='icon-ok'></i> Success!",
                                "className" : "btn-sm btn-success",
                                "callback": function() {
                                    //window.close();
                                    $("caption").eq(0).siblings().hide();
                                    $("caption").eq(1).siblings().hide();
                                    $("caption").eq(2).siblings().show();
                                    var speed=200;//滑动的速度
                                    $('body,html').animate({ scrollTop: 0 }, speed);
                                }
                            }
                        }
                    });
                }else{
                    bootbox.dialog({
                        message: "<span class='btn-sm btn-danger'>"+data.msg+"</span>"
                    });
                }
            },
            error:function(XMLHttpRequest,textStatus,errorThrown){

                bootbox.dialog({
                    message: "<span class='btn-sm btn-danger'>网络错误！</span>"
                });


            }
        });
    });

    $("#add_attr").click(function(){
        if($("#hidden_m_id").val()==''){
            var m_id = $("#m_id").val();
            if(m_id==''){
                bootbox.dialog({
                    message: "<span class='btn-sm btn-danger'>请先填写商品基本参数</span>"
                });
                return false;
            }
            id_no=1;
        }else{
            var m_id = $("#hidden_m_id").val();
            id_no=2;
        }
        var attr1=$.trim($('input[name="attr1"]').val()),
            attr2 =$.trim($("input[name='attr2']").val()),
            attr3=$.trim($("input[name='attr3']").val()),
            attr4 = $.trim($("input[name='attr4']").val()),
            attr6=$('input[name="attr6"]').val(),
            attr7=$('input[name="attr7"]').val(),
            attr8=$('input[name="attr8"]').val(),
            attr9=$('input[name="attr9"]').val(),
            attr10=$('input[name="attr10"]').val(),
            attr11=$('input[name="attr11"]').val(),
            m_video_url=$('input[name="m_video_url"]').val(),
            pre_sale_rules=encodeURIComponent(editor_pre_sale_rules.html()),
            m_special_desc=encodeURIComponent(editor_m_special_desc.html()),
            m_instructions_url=$.trim($('input[name="m_instructions_url"]').val()),
            m_multifunctional_auxiliary_part=encodeURIComponent(editor_m_multifunctional_auxiliary_part.html()),
            m_preferential_policy=$('input[name="m_preferential_policy"]').val(),
            url1=encodeURIComponent(editor_url1.html()),
            url2=encodeURIComponent(editor_url2.html()),
            url3=encodeURIComponent(editor_url3.html()),
            url4=encodeURIComponent(editor_url4.html());

        if(attr1==''){
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请先填写工作质量</span>"
            });
            return false;
        }
        if(attr2==''){
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请先填写标准斗容</span>"
            });
            return false;
        }
        if(attr3==''){
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请先填写理论油耗</span>"
            });
            return false;
        }
        if(attr4==''){
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请先填写代理商</span>"
            });
            return false;
        }
        if(attr6==''){
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请先填写发动机品牌/型号</span>"
            });
            return false;
        }
        if(attr7==''){
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请先填写主泵型号</span>"
            });
            return false;
        }

        if(attr8==''){
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请先填写主阀型号</span>"
            });
            return false;
        }

        if(attr9==''){
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请先填写行走马达型号</span>"
            });
            return false;
        }

        if(attr10==''){
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请先填写回转马达型号</span>"
            });
            return false;
        }

        if(attr11==''){
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请先填写整机产地</span>"
            });
            return false;
        }

        if(m_video_url==''){
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请先填写视频</span>"
            });
            return false;
        }
        if(m_instructions_url==''){
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请先填写说明书</span>"
            });
            return false;
        }
        if(m_preferential_policy==''){
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请先填写优惠政策</span>"
            });
            return false;
        }
        if (pre_sale_rules == '') {
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请填写预售规则！</span>"
            });
            return false;
        }
        if (m_special_desc == '') {
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请填写产品特性！</span>"
            });
            return false;
        }
        if (m_multifunctional_auxiliary_part == '') {
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请填写多功能辅件！</span>"
            });
            return false;
        }
        if (url1 == '') {
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请填写性能参数！</span>"
            });
            return false;
        }
        if (url2 == '') {
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请填写图片链接！</span>"
            });
            return false;
        }
        if (url3 == '') {
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请填写视频链接！</span>"
            });
            return false;
        }
        if (url4 == '') {
            bootbox.dialog({
                message: "<span class='btn-sm btn-danger'>请填写口碑链接！</span>"
            });
            return false;
        }

        var data={
            "m_id":m_id,"attr1":attr1, "attr2":attr2,"attr3":attr3, "attr4":attr4,
            "attr6":attr6, "attr7":attr7,"attr8":attr8, "attr9":attr9,
            "attr10":attr10, "attr11":attr11,"m_video_url":m_video_url, "pre_sale_rules":pre_sale_rules,
            "m_special_desc":m_special_desc, "m_instructions_url":m_instructions_url,"m_multifunctional_auxiliary_part":m_multifunctional_auxiliary_part,
            "m_preferential_policy":m_preferential_policy,  "url1":url1,  "url2":url2,
            "url3":url3,  "url4":url4,"id_no":id_no

        };
        var addMachine=$("#addMachine").val();
        var addHref=$("#addHref").val();
        $.ajax({
            type:"POST",
            async:false,
            dataType:"json",
            url:addMachine,
            data:data,
            success:function(data,textStatus){
                if(data.code==200){
                    bootbox.dialog({
                        message: "<span class='bigger-110'>"+data.msg+"</span>",
                        buttons:
                        {
                            "success" :
                            {
                                "label" : "<i class='icon-ok'></i> Success!",
                                "className" : "btn-sm btn-success",
                                "callback": function() {
                                    window.location.href=addHref;

                                }
                            }
                        }
                    });
                }else{
                    bootbox.dialog({
                        message: "<span class='btn-sm btn-danger'>"+data.msg+"</span>"
                    });
                }
            },
            error:function(XMLHttpRequest,textStatus,errorThrown){

                bootbox.dialog({
                    message: "<span class='btn-sm btn-danger'>网络错误！</span>"
                });


            }
        });
    });



    $("#select_all").click(function(){
        var serverIp = document.getElementById("serverIp");
        for (var i=0; i < serverIp.length; i++) {
            var val = /([0-9]{1,3}\.{1}){3}[0-9]{1,3}/;
            var vald = val.exec(serverIp[i]);
            if(vald != null ){
                serverIp[i].selected = true;
            }
        }
        $("#serverIp").trigger("chosen:updated");
    });

    upload($("a[name=file_upload]"));
    bind_del_pic();
    $("#stockchange").hide();
    $("select[name=m_tag]").change(function(){
        if($(this).val() == 1){
            $("#stockchange").show();
        } else {
            $("#stockchange").hide();
        }
    })
    if($("select[name=m_tag]").val()==1){
        $("#stockchange").show();
    }
});

function inMachineNoArr(machine_no){
    var machine_nos = machine_no_arr.split(',');
    for(var i=0;i<machine_nos.length;i++){
        if(machine_nos[i] == machine_no){
            return true;
        }
    }
    return false;
}
function  loadData(brand_id){
    var url=$("#loadDataUrl").val();
    $.post(url, { brand_id: brand_id},
        function(data){
            var obj = eval("("+data+")");
            $("#machine_no").html("");
            for(var i=0;i<obj.list.length;i++){
                if(inMachineNoArr(obj.list[i].machine_no)){
                    $("#machine_no").append("<div style='float:left;width:25%;'><input type='checkbox' name='machine_no' checked='checked' style='width:100px' value='"+obj.list[i].machine_no+"'>"+obj.list[i].machine_no+"</input></div>")
                }else{
                    $("#machine_no").append("<div style='float:left;width:25%;'><input type='checkbox' name='machine_no'  style='width:100px' value='"+obj.list[i].machine_no+"'>"+obj.list[i].machine_no+"</input></div>")
                }

            }
            if(obj.list.length == 0){
            }
        });
}
function upload(obj){
    var swf=$("#uploadSwf").val();
    var uploader=$("#uploader").val();
    $(obj).uploadify({
        'height'   : 140,
        'width'   : 140,
        'multi':true,
        'formData'      : {'file_type' : 0},
        'swf'      : swf,    //指定上传控件的主体文件
        'uploader' : uploader,    //指定服务器端上传处理文件
        'fileTypeExts': '*.jpg',  //jpeg;*.gif;*.png
        'fileTypeDesc': 'Image Files',
        'fileSizeLimit' : '4096KB',
        'buttonText':"",
        'queueSizeLimit' : 5,
        //检测FLASH失败调用
        'onFallback':function(){
            alert("您的浏览器未安装FLASH控件，无法上传图片，请安装FLASH控件后再试！");
        },
        //返回一个错误，选择文件的时候触发
        'onSelectError':function(file, errorCode, errorMsg){
            switch(errorCode) {
                case -100:
                    alert("上传的文件数量已经超出限制的"+$('a[name=file_upload]').uploadify('settings','queueSizeLimit')+"个文件！");
                    break;
                case -110:
                    alert("文件 ["+file.name+"] 大小超出系统限制的"+$('a[name=file_upload]').uploadify('settings','fileSizeLimit')+"大小！");
                    break;
                case -120:
                    alert("文件 ["+file.name+"] 大小异常！");
                    break;
                case -130:
                    alert("文件 ["+file.name+"] 类型不正确！");
                    break;
            }
        },

        'onUploadError':function(file, errorCode, errorMsg, errorString){
            alert(errorString);
        },
        'onUploadSuccess' : function(file, data, response) {
            var service_url = $("#service_url").val();;
            var jsons       = "/2013/"+data;
            //$('#' + file.id).parent().find('img').remove();

            //$('#' + file.id).parent().attr('filename',data);
            if ($(".no_pic").length > 0) {
                $(".no_pic").remove();
            }
            $("<div style='max-width:200px;height:140px;float: left;text-align: center'><input type='hidden' name='upload_files' value='"+data+"' />" +
                "<img class='preview-upload-pic' style='height:110px;max-width:160px; margin:5px;' src='"+service_url+jsons+"'/>&nbsp;" +data+"<br/><a href='javascript:void(0);' file_name='"+data+"'class='del_pic'>删除</a><br/><br/><br/></div>").insertBefore($('#' + file.id).parent());
            bind_del_pic();
        }
    });
}
function bind_del_pic(){
    $(".del_pic").click(function(){
        $(this).parent().remove();
        $("#del_attch").append("<input type='hidden' name='deled_pic[]' value='"+$(this).attr('file_name')+"' />");
    });
}